package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private WorkspaceServiceImpl workspaceServiceImpl;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {

        List<LocalDate> dates = DateList(begin,end);

        List<Double> turnovers = new ArrayList<>();
        //营业额数据统计
        for(LocalDate date : dates){
            //查询date日期对应的营业额数据
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            turnovers.add(turnover);
            //select sum(amount) from orders where order_time > and order_tiem < and status =
        }





        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .turnoverList(StringUtils.join(turnovers,","))
                .build();
    }

    @Override
    public UserReportVO getUserReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = DateList(begin,end);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for(LocalDate date : dates){
            //查询date日期对应的营业额数据
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();

            map.put("end",endTime);
            Integer totalUsers = userMapper.countByMap(map);

            map.put("begin",beginTime);
            Integer newUsers = userMapper.countByMap(map);

            totalUserList.add(totalUsers);
            newUserList.add(newUsers);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = DateList(begin,end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();




        for(LocalDate date : dates){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);


            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);

            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }



        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validTotalOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0) {
            orderCompletionRate = (double) (validTotalOrderCount / totalOrderCount);
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validTotalOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSaleTop10Report(LocalDate begindate, LocalDate enddate) {

        LocalDateTime begin = LocalDateTime.of(begindate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(enddate, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getSaleTop10(begin,end);

        List<String> names = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        //1.查询数据库，获取营业数据
        LocalDate databegin = LocalDate.now().minusDays(30);
        LocalDate databend = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceServiceImpl.getBusinessData(LocalDateTime.of(databegin, LocalTime.MIN), LocalDateTime.of(databend, LocalTime.MAX));


        //2.通过
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {

            //基于模板创建一个新的文件
            XSSFWorkbook workbook = new XSSFWorkbook(in);

            //填充数据
            XSSFSheet sheet = workbook.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间：" + databegin + "至" +  databend);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for(int i = 0; i < 30;i++){
                LocalDate date = databegin.plusDays(i);

                BusinessDataVO businessData1 = workspaceServiceImpl.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }
            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);


            outputStream.flush();
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public List<LocalDate> DateList(LocalDate begin, LocalDate end){
        //先拼接dataList
        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);
        while(!begin.equals(end)){
            //日期计算
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        return dates;
    }
}
